package com.bw.lib_widget.verify_code

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.ViewGroup
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import com.bw.lib_widget.R

/**
 * @author zhy
 * @date 2025-09-23 10:13
 * @description
 */
class VerifyCodeView: FrameLayout, OnClickListener {

    private val codeViewList: List<VerifyCodeItemView>
    private val et: EditText
    private var inputText = "" //编辑框输入的内容
    private var codeLength = 0
    private var onInputVerifyCodeCompleted: ((smsCode: String) -> Unit)? = null

    /**
     * 设置输入完毕的回调监听
     */
    fun setOnInputVerifyCodeCompleted(l: (smsCode: String) -> Unit) {
        this.onInputVerifyCodeCompleted = l
    }

    constructor(context: Context):this(context,null)
    constructor(context: Context, attrs: AttributeSet?):this(context,attrs,0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int):super(context,attrs,defStyleAttr){
        //view
        val parentView = LayoutInflater.from(context).inflate(R.layout.layout_verify_code_view, this) as ViewGroup
        codeViewList = listOf(
            parentView.findViewById(R.id.code_1),
            parentView.findViewById(R.id.code_2),
            parentView.findViewById(R.id.code_3),
            parentView.findViewById(R.id.code_4),
            parentView.findViewById(R.id.code_5),
            parentView.findViewById(R.id.code_6)
        )
        et = parentView.findViewById(R.id.et_input)
        codeLength = codeViewList.size
        //点击获得焦点
        parentView.setOnClickListener(this)

        //编辑框焦点事件
        et.setOnFocusChangeListener { v, hasFocus ->
            if (hasFocus){
                if (inputText.length < codeLength){
                    codeViewList[inputText.length].setFocus(true)
                }
            }else{
                //取消所有选中
                codeViewList.forEach {
                    it.setFocus(false)
                }
            }
        }
        //编辑框内容改变监听
        et.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            /**
             * s:改变后的文本内容
             * start:改变后的文本的起始位置
             * before:删除的数量，若是新增0
             * count:新增的数量，若是删除0
             */
            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                inputText = s.toString()
                if (before == 0){//新增内容，光标后移动
                    if (inputText.length < codeLength){
                        codeViewList[inputText.length].setFocus(true)
                    }
                    //取消之前的选中
                    if (inputText.isNotEmpty()){
                        codeViewList[inputText.length - count].setFocus(false)
                    }
                    //设置文本
                    repeat(inputText.length){
                        codeViewList[it].setNumber(inputText[it].toString())
                    }

                }else{ //删除内容，光标前移动
                    if (inputText.length < codeLength){
                        codeViewList[inputText.length].setFocus(true)
                    }
                    //取消之前选中
                    if (inputText.length + before < codeLength){
                        codeViewList[inputText.length + before].setFocus(false)
                    }
                    //清除内容
                    repeat(before){
                        codeViewList[inputText.length + it].setNumber("")
                    }

                }

                if (inputText.length == codeLength){
                    //输入完毕
                    onInputVerifyCodeCompleted?.invoke(inputText)
                    hideSoftKeyBoard()
                }

            }

            override fun afterTextChanged(s: Editable?) {

            }

        })


    }

    override fun onClick(v: View?) {
        et.requestFocus()
        showSoftKeyBoard()

    }

    fun showSoftKeyBoard() {
        val manager: InputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        postDelayed({
            et.requestFocus()
            manager.showSoftInput(et, InputMethodManager.SHOW_IMPLICIT)
        }, 300)
    }

    fun hideSoftKeyBoard() {
        et.clearFocus()
        val manager: InputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        manager.hideSoftInputFromWindow(this.windowToken, 0)
    }


    fun clear() {
        et.text.clear()
    }


    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
    }

    /**
     * 资源释放回收,当前view关闭，但是光标动画一直存在，会导致当前view无法被回收，导致内存泄露
     */
    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        codeViewList.forEach {
            it.setFocus( false)
        }

    }

}